<template>
  <div class="connector-serial-port">
    <el-form
        :model="serialPort"
        size="small" label-width="100px"  label-position="left">
      <el-form-item label="设备" width="120px">
        <el-select
            clearable
            v-model="serialPort.DataSourceId"
            @change="OnDeviceChange"
            placeholder="请选择设备"
            style="width: 90%"
        >
          <el-option
              v-for="item in optionDevices"
              :key="item.Id"
              :label="item.DeviceName"
              :value="item.Id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="值">-->
      <!--      </el-form-item>-->
      <el-form-item label="描述">
        <el-input
            v-model="serialPort.Desc"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
            style="width: 90%"
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">

import {onMounted, ref} from 'vue'

import {useFlowStore} from "@/store/modules/flow/flowStore"
// @ts-ignore
import Utils from "@/vue2-flow/src/utils/Common";
import {MessageError, MessageWarning} from "@/utils";
// @ts-ignore
import FlowNodeDataApi from "@/api/flow/FlowNodeDataApi";

const FlowStore = useFlowStore()
const serialPort = ref({DataSource: '', DataSourceId: 0, Desc: ''})
const optionDevices = FlowStore.GetDevice("SERIAL_PORT")
const currentClickNode = FlowStore.CurrentClickNode

/**
 * 选中的值
 * @param DataSourceId
 */
const OnDeviceChange = (DataSourceId: number) => {
  if (!Utils.IsEmpty(DataSourceId)) {

    let Item: any;
    Item = optionDevices.filter((o: any) => o.Id === DataSourceId)[0]

    if (Item.DeviceType !== 'SERIAL_PORT') {
      return MessageError("设备类型错误，请刷新后重试");
    }
    serialPort.value.DataSourceId = DataSourceId;
    serialPort.value.DataSource = 'SERIAL_PORT';
  }
}

const _SaveNode = (NodeName: string) => {
  const NodeForm = serialPort.value
  if (Utils.IsEmpty(NodeForm.DataSourceId) || NodeForm.DataSourceId == 0) {
    return MessageWarning('请选择设备')
  }
  const params = {
    CommonInput: {
      DataSource: NodeForm.DataSource,
      DataSourceId: NodeForm.DataSourceId,
    },
    Desc: NodeForm.Desc
  }
  new FlowNodeDataApi().Install(currentClickNode.id, params, NodeName)
}

const SetFormValue = (_node: any) => {

  if (!Utils.IsEmpty(_node?.nodeInputParam?.CommonInput)) {
    const from = {DataSource: '', DataSourceId: 0, Desc: ''}
    from.DataSource = _node.nodeInputParam.CommonInput.DataSource
    from.DataSourceId = _node.nodeInputParam.CommonInput.DataSourceId
    from.Desc = _node.nodeInputParam.Desc
    serialPort.value = from
  }
}

onMounted(()=>{
  SetFormValue(FlowStore.CurrentClickNode)
})

defineExpose({_SaveNode})
</script>

<style scoped lang="scss">
.connector-serial-port {

}
</style>
